package com.bprogram.config;

import com.bprogram.controller.UserFeign;
import com.bprogram.pojo.User;
import com.bprogram.utils.RedisUtil;
import io.jsonwebtoken.Claims;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;

import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties;
import org.springframework.util.Assert;

import javax.annotation.Resource;


public class UserRealm extends AuthorizingRealm {
    @Autowired
    private RedisUtil redisUtil;

    // 让shiro支持我们自定义的token，即如果传入的token时JWTToken则放行
    // 必须重写不然shiro会报错
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("进入了授权方法");
        SimpleAuthorizationInfo authInfo = new SimpleAuthorizationInfo();

       String jwtToken = principalCollection.toString().substring(7);
        Claims claims = JwtUtils.getClaims(jwtToken);

        String userCode = (String) claims.get("userCode");
        String userRole = (String) claims.get("role");
        System.out.println("shouquan——————————————————————————————————————"+userRole);

        authInfo.addStringPermission(userRole);
        return authInfo;
    }
//认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("进入了认证方法66666666666666666");
        System.out.println("token.getCredentials()"+token.getCredentials());
        System.out.println("token.getPrincipal()"+token.getPrincipal());

        Object credentials = token.getCredentials();

        String jwtToken =null;
        String userCode = null;
        String prefixAndJwtToken = (String) credentials; //该token包含Bearer
        if (!redisUtil.hasKey(prefixAndJwtToken)) {
            Assert.isTrue(false,"登录已失效，请先进行登录");

        }


           jwtToken = prefixAndJwtToken.substring(7);


            System.out.println("getUserCode"+JwtUtils.getClaims(jwtToken).get("userCode"));
            userCode = (String) JwtUtils.getClaims(jwtToken).get("userCode");
        if (!userCode.equals("123456")) {
            redisUtil.expire(prefixAndJwtToken,86400);
        }
        if(!redisUtil.sHasKey("userCode",userCode)){
            Assert.isTrue(false,"该用户不存在！");
        }
        //查看源码可知Object principal, Object credentials, String realmName，此处我们重写的JwtToken，将前面两个参数返回为token了
        return new SimpleAuthenticationInfo(prefixAndJwtToken, prefixAndJwtToken, this.getName());

    }



}
